package com.xiaocg.base.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author xiaocg
 */

class Share{
    private int number =0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void  incr(){
        lock.lock();
        try {
            while (number!=0){
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+" :: "+number);
            condition.signalAll();
        }catch (Exception e){

        } finally {
            lock.unlock();
        }
    }

    public void  decr(){
        lock.lock();
        try {
            while (number!=1){
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+" :: "+number);
            condition.signalAll();
        }catch (Exception e) {

        }finally {
            lock.unlock();
        }
    }
}
public class LockDemo1 {

    public static void main(String[] args) {
        Share share = new Share();
        new Thread(() -> {
            for (int i=1;i<=10;i++){
                share.incr();
            }
        },"aa").start();

        new Thread(() -> {
            for (int i=1;i<=10;i++){
                share.decr();
            }
        },"bb").start();

        new Thread(() -> {
            for (int i=1;i<=10;i++){
                share.incr();
            }
        },"cc").start();

        new Thread(() -> {
            for (int i=1;i<=10;i++){
                share.decr();
            }
        },"dd").start();
    }
}
